package com.example.alibabavodossservice.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.example.alibabavodossservice.publicVo.OssUploadResponse;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.example.alibabavodossservice.oss.OssConfig.*;


/**
 * desc:[该工具无需实例化] [该工具无需实例化] [该工具无需实例化]
 * [该工具无需实例化] [该工具无需实例化] [该工具无需实例化]
 * [该工具无需实例化] [该工具无需实例化] [该工具无需实例化]
 *
 * @author xugenyin
 */
public class OssTools {

    private static final ThreadLocal<OSS> OSS_THREAD_LOCAL = new ThreadLocal<>();
    public static final String SPLIT_REGEX = "https://";

    public static final String COM_PATTERN = "(?<=com/).*";


    /**
     * 获取OSSClient实例
     *
     * @return oss实例
     */
    public static OSS getOssClient() {
        OSS ossClient = OSS_THREAD_LOCAL.get();
        if (ossClient == null) {
            ossClient = new OSSClientBuilder().build(OssConfig.OSS_END_POINT, OssConfig.OSS_ACCESS_KEY_ID, OssConfig.OSS_ACCESS_KEY_SECRET);
            OSS_THREAD_LOCAL.set(ossClient);
        }
        return ossClient;
    }

    /**
     * @param file 文件
     * @return OssUploadResponse 上传结果
     */
    public static OssUploadResponse uploadFile(MultipartFile file) {
        OSS ossClient = getOssClient();
        String fileExtension = FileUtil.getFileExtension(file);
        //1.设置路径
        String bathPath = BASE_PATH + fileExtension;
        //2.设置文件名==原文件名
        String createFileName = file.getOriginalFilename();
        String fileName= bathPath + "/" + createFileName;
        try (InputStream inputStream = file.getInputStream()) {
            //3.上传
            new Thread(() -> ossClient.putObject(OSS_BUCKET_NAME, fileName, inputStream)).start();
        } catch (IOException e) {
            // 这里不应该抛出异常，因为这里是异步上传，抛出异常会导致前端无法获取到上传结果
            System.out.println(e.getMessage());
        } finally {
            OSS_THREAD_LOCAL.remove();
        }
        String ossUrl = (LAST_URL + fileName).trim();
        OssUploadResponse ossUploadResponse = new OssUploadResponse();
        ossUploadResponse.setOssUrl(ossUrl);
        ossUploadResponse.setFilePath(bathPath.trim());
        ossUploadResponse.setFileName(file.getOriginalFilename().trim());
        return ossUploadResponse;
    }

    /**
     * OSS删除指定文件
     * @param url 文件url
     */
    public static boolean deleteOssFile(String url) {
        Pattern pattern = Pattern.compile(COM_PATTERN);
            OSS ossClient = getOssClient();
            Matcher m = pattern.matcher(url);
            String result = null;
            if (m.find()) {
                result = m.group();
            }
            try {
                ossClient.deleteObject(OSS_BUCKET_NAME, result);
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
                OSS_THREAD_LOCAL.remove();
            }
        return true;
    }

    /**
     * String类型转换为MultipartFile类型
     *
     * @param filename 文件名
     * @param content  内容
     * @return MultipartFile
     */
    public static MultipartFile createMdFileFromString(String filename, String content) {
        byte[] bytes = content.getBytes();
        String originalFilename = filename + ".md";
        String contentType = "text/plain";
        return new MockMultipartFile(filename, originalFilename, contentType, bytes);
    }

}
